﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace AutoUpdate.Helper
{
    //操作共享盘
    public class ShareDiskHelper
    {
        private string _targetFolder;

        public string TargetFolder
        {
            get { return _targetFolder; }
            set { _targetFolder = value; }
        }
        private string _userName;

        public string UserName
        {
            get { return _userName; }
            set { _userName = value; }
        }
        private string _password;

        public string Password
        {
            private get { return _password; }
            set { _password = value; }
        }

        public ShareDiskHelper(string targetFolder, string userName, string password)
        {
            _targetFolder = targetFolder;
            _userName = userName;
            _password = password;
        }

        private const int RESOURCETYPE_DISK = 0x00000001;

        [StructLayout(LayoutKind.Sequential)]
        struct NETRESOURCE
        {
            public int dwScope;
            public int dwType;
            public int dwDisplayType;
            public int dwUsage;
            public string lpLocalName;
            public string lpRemoteName;
            public string lpComment;
            public string lpProvider;
        }
        //调用Window API的辅助类
        //, CharSet = CharSet.Ansi, EntryPoint = "WNetAddConnection2", CallingConvention = CallingConvention.Cdecl
        [DllImport("mpr.dll")]
        static extern int WNetAddConnection2(ref NETRESOURCE retResource, string password, string username, int flags);

        //, CharSet = CharSet.Ansi, EntryPoint = "WNetCancelConnection2", CallingConvention = CallingConvention.Cdecl
        [DllImport("mpr.dll")]
        static extern int WNetCancelConnection2(string name, int flags, bool force);

        //连接共享盘
        public bool Connect()
        {
            try
            {
                var netResource = new NETRESOURCE
                {
                    dwType = RESOURCETYPE_DISK,
                    lpRemoteName = TargetFolder
                };
                // 创建网络访问凭据对象
                var result = WNetAddConnection2(ref netResource, Password, UserName, 0);
                return result == 0 ? true : false;
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(ex.Message, ex);//record log
                throw new Exception(ex.Message);
            }

        }
        //断开共享盘
        public void Disconnect()
        {
            try
            {
                WNetCancelConnection2(TargetFolder, 0, true);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }
    }
}
